package com.wiz.weixin.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.wiz.weixin.common.Constant;
import com.wiz.weixin.manager.HttpManager;
import com.wiz.weixin.mapper.MemberMapper;
import com.wiz.weixin.mapper.StationMapper;
import com.wiz.weixin.mapper.VerificationCodeMapper;
import com.wiz.weixin.service.MemberService;
import com.wiz.weixin.to.HQBaseInfoTO;
import com.wiz.weixin.to.StationTO;
import com.wiz.weixin.util.MD5Util;
import com.wiz.weixin.util.PageView;
import com.wiz.weixin.vo.AmountHistoryVO;
import com.wiz.weixin.vo.MemberVO;
import com.wiz.weixin.vo.ResultVO;

@Service("memberService")
public class MemberServiceImpl implements MemberService {
	private transient final Logger log = LoggerFactory.getLogger(getClass());
	
//	@Resource
//	private Gson gson;
	private Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
	@Resource
	private HttpManager httpManager;
	@Resource
	private StationMapper stationMapper;
	@Resource
	private VerificationCodeMapper verificationCodeMapper;
	@Resource
	private MemberMapper memberMapper;
	
	@Override
	public ResultVO register(MemberVO member,int code, StationTO stationTO) throws Exception{
		int count = verificationCodeMapper.getCntCode(member.getPhoneNum(), code);
		if(count != 1){
			return new ResultVO(1,"验证码失效");
		}
		//查询会员信息
		List<NameValuePair> formparams = new ArrayList<NameValuePair>();  
		formparams.add(new BasicNameValuePair("HQId", stationTO.getHqId()));
		formparams.add(new BasicNameValuePair("HQName", stationTO.getHqName()));
		formparams.add(new BasicNameValuePair("stationId", stationTO.getStationId()));
		formparams.add(new BasicNameValuePair("stationName", stationTO.getStationName()));
		formparams.add(new BasicNameValuePair("memberName", member.getName()));
		formparams.add(new BasicNameValuePair("fuellingPw", member.getFuellingPw()));
		formparams.add(new BasicNameValuePair("licensePlate", member.getLicensePlate()));
		formparams.add(new BasicNameValuePair("phoneNum", member.getPhoneNum()));
		formparams.add(new BasicNameValuePair("idCard", member.getIdCard()));
		formparams.add(new BasicNameValuePair("openId", member.getOpenId()));
		formparams.add(new BasicNameValuePair("sourceType", "3"));
		
		String password =  member.getFuellingPw();
		if(StringUtils.isNotBlank(password)){
			formparams.add(new BasicNameValuePair("isCheckFuellingPw", "1"));
		}else{
			formparams.add(new BasicNameValuePair("isCheckFuellingPw", "0"));
		}
    	String response = httpManager.getResponseByHttpPost(Constant.ADD_MEMBER_URL, formparams);
    	log.info("register response="+response+",  params="+formparams.toString());
    	return gson.fromJson(response,new TypeToken<ResultVO>(){}.getType());
	}
	
	@Override
	public MemberVO getMemberByOpenId(String openId, String hqId) throws Exception {
		List<NameValuePair> formparams = new ArrayList<NameValuePair>();
		formparams.add(new BasicNameValuePair("HQId", hqId));
		formparams.add(new BasicNameValuePair("openId", openId));
		// 调用接口
    	String response = httpManager.getResponseByHttpPost(Constant.QUERY_MEMBER_URL, formparams);
    	List<MemberVO> list = null;
		JSONObject json = new JSONObject(response);
		if(!json.isNull("code")){
			String codes = json.getString("code");
			if(codes.equals("0")){
				JSONObject data = json.getJSONObject("data");
				String str = data.getString("list");
				list = gson.fromJson(str,new TypeToken<List<MemberVO>>(){}.getType());
			}
		}
    	if(list != null && list.size()>0){
    		return list.get(0);
    	}
    	return null;
	}
	
	@Override
	public List<MemberVO> listMemberByOpenId(String openId) throws Exception {
		List<MemberVO> list = null;
		List<NameValuePair> formparams = new ArrayList<NameValuePair>();
		formparams.add(new BasicNameValuePair("openId", openId));
		String result = httpManager.getResponseByHttpPost(Constant.QUERY_MEMBER_URL, formparams);
		JSONObject json = new JSONObject(result);
		if(!json.isNull("code")){
			String codes = json.getString("code");
			if(codes.equals("0")){
				JSONObject data = json.getJSONObject("data");
				String str = data.getString("list");
				list = gson.fromJson(str,new TypeToken<List<MemberVO>>(){}.getType());
			}
		}
		return list;
	}
	
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class, isolation = Isolation.DEFAULT)
	public void memberHqConfig(List<MemberVO> memberList) throws Exception {
		for(MemberVO vo : memberList){
			HQBaseInfoTO hqTO = stationMapper.getHqConfigById(vo.getHQId());
			vo.setChargeStatus(hqTO.getChargeStatus());
		}
	}
	
	@Override
	public PageView listAmountHistory(String hqId,String memberId,int pageNo,int pageSize) throws Exception {
		PageView pageView = new PageView(pageSize, pageNo);
		List<NameValuePair> formparams = new ArrayList<NameValuePair>();
		formparams.add(new BasicNameValuePair("HQId", hqId));
		formparams.add(new BasicNameValuePair("memberId", memberId));
		formparams.add(new BasicNameValuePair("pn", String.valueOf(pageView.getPageNow())));
		formparams.add(new BasicNameValuePair("ps", String.valueOf(pageView.getPageSize())));
		String result = httpManager.getResponseByHttpPost(Constant.LIST_AMOUNT_HISTORY, formparams);
		log.info("remote listAmountHistory response="+result+"  params:pageNo="+pageNo+",pageSize="+pageSize);
		JSONObject json = new JSONObject(result);
		if(!json.isNull("code")){
			String codes = json.getString("code");
			if(codes.equals("0")){
				JSONObject data = json.getJSONObject("data");
				String str = data.getString("list");
				List<AmountHistoryVO> list = gson.fromJson(str,new TypeToken<List<AmountHistoryVO>>(){}.getType());
				int total = data.getInt("recordCnt");
				pageView.setRowCount(total);
				int pageCount = 0;
				if(total%pageSize==0){
					pageCount = total/pageSize;
				}else{
					pageCount = total/pageSize+1;
				}
				pageView.setPageCount(pageCount);
				pageView.setRecords(list);
			}
		}
		pageView.setCode(200);
//		String returnResult = gson.toJson(pageView);
//		log.info(memberId+" listAmountHistory result="+returnResult);
		return pageView;
	}
	
	@Override
	public int checkMemberPassword(String memberId, String password){
		return memberMapper.checkMemberPassword(memberId, MD5Util.encode(memberId+password));
	}
	
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class, isolation = Isolation.DEFAULT)
	public int bindOpenId(String hqId, String memberId, String openId){
		if(memberMapper.checkMemberBind(hqId,memberId,openId)>0){
			return -1;
		}
		return memberMapper.bindOpenId(memberId, openId, hqId);
	}
}
